package com.ccx.demo.Controller;

import com.ccx.demo.Handler.LoginService;
import com.ccx.demo.Vo.Result;
import com.ccx.demo.Vo.ResultService;
import com.ccx.demo.pojo.SysUser;
import com.ccx.demo.service.CaptchaService;
import com.ccx.demo.service.SysUserService;
import com.ccx.demo.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class viewController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private ResultService resultService;
    @PostMapping("/login")
    public Map login(SysUser user,String code){

        System.out.println("验证码为："+code);
        if (captchaService.QueryCaptcha(code)!=null) {
            return loginService.login(user.getUsername(),user.getPassword());
        }
        else{
            Map<String,Object> map=new HashMap<>();
            map.put("code",444);
            map.put("msg","验证码错误");
            return map;
        }
    }

    @PostMapping("/register")
    public Map register( SysUser user,Integer RoleCode){
        System.out.println(RoleCode);
        System.out.println(user.getUsername());
        Map<String,Object> map=new HashMap<>();
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        try {
            sysUserService.addUser(user);
            SysUser sysUser = sysUserService.SelectUsernameByName(user.getUsername());
            boolean c = sysUserService.addUserRole(sysUser.getId(), RoleCode);
            if (c) {
                map.put("code", 200);
                map.put("msg", "添加成功");
            }
        }catch (Exception e){
            map.put("code",405);
            map.put("msg","添加失败");
        }
        return map;
    }
    @PreAuthorize("hasAuthority('index')")
    @GetMapping("/index")
    public Result index(int page,int limit){
        try {
            return resultService.PAGE(page, limit);
        }catch (Exception e){
            return resultService.FAIL();
        }
    }
    @PreAuthorize("hasAuthority('mm')")
    @GetMapping("/mm")
    public Result queryPage(int page,int limit){
        return resultService.PAGE(page, limit);
    }
    @PreAuthorize("hasAnyAuthority('download')")
    @GetMapping("/download")
    public String download(){
        return "download";
    }
}
